package org.cqut.system.class_course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.cqut.system.class_course.bo.ClassListBo;
import org.cqut.system.class_course.domain.ClassCourse;
import org.cqut.system.class_course.mapper.ClassCourseMapper;
import org.cqut.system.class_course.service.ClassCourseService;
import org.cqut.system.class_course.vo.ClassListVo;
import org.cqut.system.clazz.bo.ClassBo;
import org.cqut.system.clazz.mapper.ClazzMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author XiAoXu
 */
@Service
public class ClassCourseServiceImpl extends ServiceImpl<ClassCourseMapper, ClassCourse>
        implements ClassCourseService {

    private final ClassCourseMapper classCourseMapper;

    private final ClazzMapper clazzMapper;

    public ClassCourseServiceImpl(ClassCourseMapper courseMapper, ClazzMapper clazzMapper) {
        this.classCourseMapper = courseMapper;
        this.clazzMapper = clazzMapper;
    }

    @Override
    public List<ClassListVo> getRecordByCourseId(Long courseId) {
        //[班级编号/班级名/时间]
        List<ClassListBo> classCourseBos = classCourseMapper.selectClassListVoByCourseId(courseId);
        //如果没有班级则直接返回
        if (classCourseBos.isEmpty()) {
            return new ArrayList<>();
        }
        //取出classId
        List<Long> ids = classCourseBos.stream().map(ClassListBo::getClassId).collect(Collectors.toList());
        //查出 [班级名/总人数]
        List<ClassBo> clsBo = clazzMapper.selectClassNumberByIds(ids);
        //封装到Vo
        List<ClassListVo> view = new ArrayList<>();

        for (ClassListBo classCourseBo : classCourseBos) {
            ClassListVo classListVo = new ClassListVo();
            classListVo.setClassId(classCourseBo.getClassId());
            classListVo.setClassName(classCourseBo.getClassName());
            classListVo.setJoinTime(classCourseBo.getCreateTime());

            for (ClassBo classBo : clsBo) {
                if (Objects.equals(classBo.getClassName(), classCourseBo.getClassName())) {
                    classListVo.setClassNumber(classBo.getClassNumber());
                    break;
                }
            }
            view.add(classListVo);
        }

        return view;
    }

    @Override
    public boolean removeByClassIdAndCourseId(ClassCourse classCourse) {
        QueryWrapper<ClassCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classCourse.getClassId()).eq("course_id", classCourse.getCourseId());
        return remove(queryWrapper);
    }
}




